#!/bin/bash

# Copyright (c) 2022 az13js
# new_program & new_program_server is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of
# the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#          http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF
# ANY KIND,EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
# NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.

# 临时用来测试用的脚本

function kill_new_program_server() {
    SERVER_PID=`pgrep -a -f bin/new_program_server | cut -d " " -f 1`
    if [ ! -z "$SERVER_PID" ]
    then
        kill "$SERVER_PID"
        SERVER_PID=`pgrep -a -f bin/new_program_server | cut -d " " -f 1`
        if [ ! -z "$SERVER_PID" ]
        then
            echo "Kill FAIL!" >&2
            echo "pgrep -a -f bin/new_program_server" >&2
            pgrep -a -f bin/new_program_server >&2
            exit 1
        fi
    fi
}

echo "首先终止已有的 new_program_server"
kill_new_program_server

rm -rf bin
mkdir bin
g++ -o bin/new_program_server new_program_server.cpp -lpthread
g++ -o bin/new_program new_program.cpp
g++ -o bin/test_program test_program.cpp
if [ -z "$PATH" ]
then
    export PATH="bin"
else
    export PATH="bin:$PATH"
fi

export NEW_PROGRAM_SOCKET_FILE="bin/new_program_server.sock"
export NEW_PROGRAM_LOG_FILE="bin/new_program_server.log"

echo "开始"
bin/new_program_server >bin/new_program_server_console.log &
sleep 1
for ((i=0;i<3;i++))
do
    bash test_thread.sh>/dev/null &
done
bash test_thread.sh>/dev/null

while true
do
    sleep 3
    COUNT_PRO=`pgrep -a -f test_program -c`
    if [ "$COUNT_PRO" -eq "0" ]
    then
        break
    fi
done

kill_new_program_server

rm -f bin/test_data.log
for file in bin/*.txt
do
    cat $file >>bin/test_data.log
done

sort bin/test_data.log>bin/test_data_sort.log
echo "调用的程序的执行情况"
tail bin/test_data_sort.log
echo "调用的程序的执行次数"
wc -l bin/test_data_sort.log
echo "调用的程序的执行最大并发情况（毫秒）"
cut bin/test_data_sort.log -d " " -f 1 | uniq -c | sort -bnr -t " " | head
echo "调用的程序的执行最大并发情况（秒）"
cut bin/test_data_sort.log -d " " -f 1 | cut -d "." -f 1 | uniq -c | sort -bnr -t " " | head

